<?php
namespace app\service;

use think\Db;
use think\Cookie;
use think\Config;

/**
 * User Service Class
 * Handles user registration, login and authentication related features
 */
class UserService
{

    private function _generateUserId(){
        $user_id = date('YmdHis');
        return $user_id;
    }

    public function getUserId(){
        $cookie_key = config('auth.cookie_key');
        // 从Cookie中获取加密的用户ID
        $encrypted_user_id = Cookie::get($cookie_key);
        $user_id = null;
        
        // 如果Cookie中存在token，尝试解密
        if($encrypted_user_id){
            // 获取配置文件中的salt
            $salt = config('auth.cookie_salt');
            
            // 解密用户ID
            $user_id = $this->decryptUserId($encrypted_user_id, $salt);
        }
        
        // 如果没有获取到有效的user_id，生成一个新的并设置cookie
        if (!$user_id) {
            $user_id = $this->_generateUserId(); 
            $this->_setCookieUserId($user_id);
        }
        
        return $user_id;
    }
    
    private function _setCookieUserId($user_id){
        // 获取配置文件中的salt
        $salt = config('auth.cookie_salt');
        $cookie_key = config('auth.cookie_key');
        
        
        // 生成加密的用户ID
        $encrypted_user_id = $this->encryptUserId($user_id, $salt);
        
        // Set cookie - 使用相对时间（秒数）而非绝对时间戳
        $expireTime = 86400 * 3650; // 10年的秒数
        Cookie::set($cookie_key, $encrypted_user_id, [
            'expire' => $expireTime,
            'httponly' => true,
            'secure' => request()->isSsl() // 如果是HTTPS则设置secure标志
        ]);
    }
    /**
     * 加密用户ID
     * @param int $user_id 用户ID
     * @param string $salt 加密盐
     * @return string 加密后的用户ID
     */
    private function encryptUserId($user_id, $salt) {
        // 生成一个随机的初始化向量
        $iv = substr(md5(microtime()), 0, 16);
        
        // 将用户ID和时间戳组合起来，增加安全性
        $data = $user_id . '|' . time();
        
        // 使用AES-256-CBC加密
        $encrypted = openssl_encrypt($data, 'AES-256-CBC', $salt, 0, $iv);
        
        // 将IV和加密后的数据拼接起来，并进行Base64编码
        return base64_encode($iv . $encrypted);
    }
    
    /**
     * 解密用户ID
     * @param string $encrypted_user_id 加密后的用户ID
     * @param string $salt 加密盐
     * @return int|null 解密后的用户ID，解密失败返回null
     */
    private function decryptUserId($encrypted_user_id, $salt) {
        try {
            if (empty($encrypted_user_id)) {
                return null;
            }
            
            // Base64解码
            $data = base64_decode($encrypted_user_id);
            if ($data === false) {
                return null;
            }
            
            // 提取IV（前16个字符）
            if (strlen($data) <= 16) {
                return null;
            }
            
            $iv = substr($data, 0, 16);
            
            // 获取加密后的数据
            $encrypted = substr($data, 16);
            
            // 解密
            $decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $salt, 0, $iv);
            
            if ($decrypted === false) {
                return null;
            }
            
            // 分离用户ID和时间戳
            $parts = explode('|', $decrypted);
            if (count($parts) !== 2) {
                return null;
            }
            
            list($user_id, $timestamp) = $parts;
            
            return (int)$user_id;
        } catch (\Exception $e) {
            // 解密失败
            return null;
        }
    }
    public function getUserInfo(){
        $user_id = $this->getUserId();
        $user_info = Db::name('users')->where('id', $user_id)->find();
        if (empty($user_info)){
            return [
                'user_id' => $user_id,
                'nickname' => '遊客用戶',
                'avatar' => '',
                'google_id' => '',
                'user_type' => 'guest',
            ];
        }
        return [
            'user_id' => $user_info['id'],
            'nickname' => $user_info['nickname'],
            'avatar' => $user_info['avatar'],
            'google_id' => $user_info['google_id'],
            'user_type' => 'user',
        ];
    }

    private function _syncLocalUserToGoogleUser($origin_user_id){
        
        $user_id = $this->getUserId();
        // 设置原始用户ID
        $this->_setCookieUserId($origin_user_id);

        $operations_list = Db::name('operations')->where(['user_id'=>$user_id])->select();
        foreach ($operations_list as $operations){
            $operations['user_id'] = $origin_user_id;
            Db::name('operations')->where(['id'=>$operations['id']])->update($operations);
        }
        $wallpaper_generate_list = Db::name('wallpaper_generate')->where(['user_id'=>$user_id])->select();
        foreach ($wallpaper_generate_list as $wallpaper_generate){
            $wallpaper_generate['user_id'] = $origin_user_id;
            Db::name('wallpaper_generate')->where(['id'=>$wallpaper_generate['id']])->update($wallpaper_generate);
        }
        


    }
    /**
     * Create or update Google user
     * @param string $googleId Google ID
     * @param string $email User email
     * @param string $nickname User nickname
     * @param string $avatar User avatar
     * @return array
     */
    public function createOrUpdateGoogleUser($googleId, $email, $nickname, $avatar = '')
    {
        // Check if Google ID already exists
        $user = Db::name('users')->where('google_id', $googleId)->find();
        
        // If Google ID doesn't exist, check if email exists
        if (!$user && $email) {
            $user = Db::name('users')->where('email', $email)->find();
        }
        
        $now = date('Y-m-d H:i:s');
        
        // If user exists, update information
        if ($user) {
            $updateData = [
                'google_id' => $googleId,
                'nickname' => $nickname ?: $user['nickname'],
                'avatar' => $avatar ?: $user['avatar'],
                'auth_type' => 2, // Google authentication
                'status' => 1,
                'updated_at' => $now
            ];
            
            Db::name('users')->where('id', $user['id'])->update($updateData);
            $userId = $user['id'];
            $this->_syncLocalUserToGoogleUser($userId);
        } else {
            // Create new user
            $userData = [
                'id' => $this->getUserId(),
                'nickname' => $nickname ?: explode('@', $email)[0],
                'email' => $email,
                'google_id' => $googleId,
                'avatar' => $avatar ?: $this->getDefaultAvatar($nickname),
                'auth_type' => 2, // Google authentication
                'status' => 1,
                'created_at' => $now,
                'updated_at' => $now
            ];
            
            $success = Db::name('users')->insert($userData);
            if ($success) {
                $userId = $userData['id'];
            }
        }
        
        if ($userId) {
            $user = Db::name('users')->where('id', $userId)->find();
            return [
                'status' => true, 
                'message' => '綁定成功', 
                'data' => [
                    'user_id' => $userId,
                    'nickname' => $user['nickname'],
                    'email' => $user['email'],
                    'avatar' => $user['avatar']
                ]
            ];
        } else {
            return ['status' => false, 'message' => '綁定失敗，請稍後再試'];
        }
    }
    /**
     * Get default avatar
     * @param string $nickname User nickname
     * @return string Default avatar URL
     */
    protected function getDefaultAvatar($nickname)
    {
        // Generate color hash based on nickname
        $hash = md5($nickname);
        $color = substr($hash, 0, 6);
        
        // Use Gravatar or other service to generate default avatar
        return "https://www.gravatar.com/avatar/" . $hash . "?d=identicon&s=200";
    }
   
}